#include <pthread.h>
#include <cassert>
#include <strings.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"

void Usage(const std::string name)
{
    std::cout << "Usage:\n\t" << name << " server_ip server_port" << std::endl;
    exit(3);
}
void *receiverAndPrint(void *args)
{
    while (true)
    {
        int sockfd = *(int *)args;
        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s=recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
        if(s>0)
        {
            buffer[s]=0;
            std::cout<<"sever echo# "<<buffer<<std::endl;
        }
    }
}
// ./udpClient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
    }
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    assert(sockfd > 0);
    pthread_t t;
    pthread_create(&t, nullptr, receiverAndPrint, (void *)&sockfd);
    // 填服务器信息
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_port = htons(server_port);
    std::string buffer;
    while (true)
    {
        std::cout << "Please Enter# ";
        getline(std::cin, buffer);
        sendto(sockfd, buffer.c_str(), buffer.size(), 0, (struct sockaddr *)&server,
               sizeof(server));
    }
    return 0;
}